<?php
namespace App\Services\PingAnPay;

use App\Services\PingAnPay\lib\pingan;
use App\Services\PingAnPay\lib\pingan_quick;


/**
* 发起后台支付交易（UnionAPI_Submit）
*/
const SEND_URL = 'http://testebank.sdb.com.cn/khpayment/UnionAPI_Submit.do';
//如果手机端出现证书过期，可以使用http://testebank.orangebank.com.cn/khpayment/UnionAPI_Submit.do

class UnionApiSubmit
{

	/**
	 * [pay description]
	 * @param  [varchar]  [30]    $customerId 	[商户会员号]
	 * @param  [varchar]  [30]    $orderId    	[订单号，严格遵守格式：商户号+8位日期YYYYMMDD+8位流水，唯一性，需与发起短信验证码交易的一致]
	 * @param  [varchar]  [14]    $paydate    	[单时间，YYYYMMDDHHMMSS，需与发起短信验证码交易的一致]
	 * @param  [number]   [12,2]  $amount     	[订单金额，12整数，2小数]
	 * @param  [varchar]  [200]   $objectName 	[订单款项描述（商户自定）]
	 * @param  [varchar]  [26]    $openId     	[开通银行卡Id]
	 * @param  [number]   [6]     $verifyCode 	[短信验证码]
	 * @param  [number]   [10]    $validtime  	[订单有效期(毫秒)，0不生效]
	 * @return [type]              [description]
	 */
	public function pay($customerId, $order_id, $orderId, $paydate, $amount, $objectName, $openId, $verifyCode, $validtime=0)
	{

		// $pingan = new pingan ();
        $pingan = new pingan_quick();
		$notify_url = 'http://www.baidu.com';

		$data = array (
                'masterId' => config('pinganpay.masterId'),         //商户号，长度：10
				'orderId' => $orderId,								//订单号，严格遵守格式：商户号+8位日期YYYYMMDD+8位流水，唯一性，需与发起短信验证码交易的一致，长度：26
				'currency' => 'RMB',								//币种，目前只支持RMB，长度：3
				'amount' => $amount,								//订单金额，12整数，2小数
				'objectName' => $objectName,						//订单款项描述（商户自定）,长度：200
				'paydate' => $paydate,								//下单时间，YYYYMMDDHHMMSS，需与发起短信验证码交易的一致
				'validtime' => $validtime,									//订单有效期(毫秒)，0不生效
				'remark' => 'remark',								//备注字段（商户自定），可为空
				'customerId' => $customerId,						//商户会员号,长度：30
				'OpenId' => $openId,								//开通银行卡Id,长度：26
				'NOTIFYURL' => $notify_url,							//异步通知地址
				'verifyCode' => $verifyCode				//短信验证码
		);

		// $data = array (
		// 		'masterId' => 'unionpay01',
		// 		'orderId' => 'unionpay012016052758494889',
		// 		'currency' => 'RMB',
		// 		'amount' => '100.09',
		// 		'objectName' => 'test',
		// 		'paydate' => '20160527031756',
		// 		'validtime' => '0',
		// 		'remark' => 'test',
		// 		'customerId' => '0001',
		// 		'OpenId' => 'unionpay012016052743419513',
		// 		'NOTIFYURL' => $notify_url,
		// 		'verifyCode' => '111111'
		// );

		$xml_data = $pingan->array_to_xml ( $data );
		// $merchantCertFile = '../merchant/2000311146.pfx';
        $merchantCertFile = config('pinganpay.merchant_cert_file');

		// 获取签名后的orig和sign
		$orig = $pingan->getOrig ( $xml_data );
		$sign = $pingan->getSign ( $merchantCertFile, $xml_data );

		// 通过curl请求接口
		$parms = 'orig=' . $orig . '&sign=' . $sign;
		$rsponse = $pingan->curl ( SEND_URL, $parms );

		// 通过字符串截取获取orig
		$rsponseData = explode ( 'orig=', $rsponse );
		$rsponse2Data = explode ( 'SDBPAYGATE=', $rsponseData [1] );

		$rsponseSign = explode ( 'sign=', $rsponse );
		$rsponse2Sign = explode ( 'orig=', $rsponseSign [0] );

		// 解码
		$formOrig = $pingan->_base64_url_decode ( $rsponse2Data [0] );
		$formSign = $pingan->_base64_url_decode ( $rsponse2Sign [0] );
		// $tTrustPayCertFile = 'merchant/paygate.cer';
        $tTrustPayCertFile = config('pinganpay.t_trust_pay_cert_file');

		//2、验证签名是否正确
		$result = $pingan->validate($formOrig, $formSign, $tTrustPayCertFile);
		if ($result) {
		    // echo 'success';
		} else {
		    // exit('error');
            return false;
		}
		// $xml_dom = str_replace("GBK", "utf-8", $formOrig);
		// $result = $pingan->xml_to_array($xml_dom);
		// 输出结果
		$formOrig = iconv("GBK", "UTF-8", $formOrig);
		$orig_data = $pingan->xml_to_array_bak($formOrig);

		/**
		{ ["errorCode"]=> string(0) ""
		["errorMsg"]=> string(0) ""
		["masterId"]=> string(10) "unionpay01"
		["orderId"]=> string(26) "unionpay012016052758494889"
		["currency"]=> string(3) "RMB"
		["amount"]=> string(6) "100.09"
		["paydate"]=> string(14) "20160527031756"
		["remark"]=> string(4) "test"
		["objectName"]=> string(4) "test"
		["validtime"]=> string(0) ""
		["status"]=> string(2) "01"
		["date"]=> string(14) "20160526000100"
		["charge"]=> string(4) "0.30"
		 ["accNo"]=> string(4) "0018"
		 ["telephone"]=> string(11) "135****5506"
		  ["customerId"]=> string(4) "0001" }
		 * */

		// var_dump($orig_data);
		// echo json_encode($orig_data);
		return $orig_data;
	}
}
?>

